package com.guigu.gulisearch.service.impl;

import com.guigu.gulicommon.entity.pojo.AttrsPoJo;
import com.guigu.gulicommon.entity.pojo.res.Res;
import com.guigu.gulicommon.entity.vo.es.SkuEsModel;
import com.guigu.gulisearch.entity.ProductEs;
import com.guigu.gulisearch.mapper.ProductEsMapper;
import com.guigu.gulisearch.service.ProductEsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.guigu.gulicommon.constant.enumes.res.AddResCode.INSERT_PRODUCT_TO_ES_SUCCESS;

/**
 * 商品保存服务
 *
 * @author 陈俊杰
 * @version 1.0
 * @since 2024/8/25 22:32
 */
@Slf4j
@Service
public class ProductEsServiceImpl implements ProductEsService {

    @Autowired
    private ProductEsMapper productEsMapper;

    /**
     * 保存单款商品信息到ES
     *
     * @param skuEsModels 商品信息集合
     * @return 保存结果
     */
    @Override
    public Res<SkuEsModel> saveProduct(List<SkuEsModel> skuEsModels) {
        List<ProductEs> productEsList = skuEsModels.stream().map(skuEsModel -> {
            ProductEs productEs = new ProductEs();
            BeanUtils.copyProperties(skuEsModel, productEs);
            List<AttrsPoJo> attrsList = skuEsModel.getAttrs().stream().map(skuEsModelAttr -> {
                AttrsPoJo attrs = new AttrsPoJo();
                BeanUtils.copyProperties(skuEsModelAttr, attrs);
                return attrs;
            }).collect(Collectors.toList());
            productEs.setAttrs(attrsList);
            // 设置主键
            productEs.setId(skuEsModel.getSkuId());
            return productEs;
        }).collect(Collectors.toList());
        log.info("保存商品信息到ES:{}", productEsList);
        productEsMapper.insertBatch(productEsList);

        return new Res<>(INSERT_PRODUCT_TO_ES_SUCCESS, skuEsModels);
    }
}
